package org.jeecg.modules.demo.pcl.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.pcl.entity.CmsZhuisuTree;
import org.jeecg.modules.demo.pcl.service.ICmsZhuisuTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

 /**
 * @Description: CMS-追溯系统-查询
 * @Author: jeecg-boot
 * @Date:   2025-01-15
 * @Version: V1.0
 */
@Api(tags="CMS-追溯系统-查询")
@RestController
@RequestMapping("/pcl/cmsZhuisuTree")
@Slf4j
public class CmsZhuisuTreeController extends JeecgController<CmsZhuisuTree, ICmsZhuisuTreeService>{
	@Autowired
	private ICmsZhuisuTreeService cmsZhuisuTreeService;

	 private static final String DB_URL = "jdbc:as400://10.224.80.16;naming=system;libraries=S78AF550;translate binary=true;";
	 private static final String USER = "Hand_mes";
	 private static final String PASSWORD = "Hand_mes@";
	 /**
	  * 主查询树
	  */
	 //@AutoLog(value = "CMS-追溯系统-查询-分页列表查询")
	 @ApiOperation(value = "CMS-追溯系统-查询-主查询树", notes = "CMS-追溯系统-查询-主查询树")
	 @GetMapping(value = "/queryParam")
	 public Result<List<Node>> queryParam(@RequestParam(required = false) String query, HttpServletRequest req) {
		 if (oConvertUtils.isEmpty(query)){
			 return Result.error("请输入序列号！");
		 }
		 // 设置默认时区为本地时区
		 TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); // 根据实际情况设置时区

		 // 注册 JDBC 驱动程序
		 try {
			 Class.forName("com.ibm.as400.access.AS400JDBCDriver");
		 } catch (ClassNotFoundException e) {
			 e.printStackTrace();
		 }

		 Node root = null;
		 try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
			  PreparedStatement pst = connection.prepareStatement(
					  "SELECT J0ASER, J0STIM, J0APRT, J0ALOT,DECIMAL(s2.HWQTY,10,2) AS HWQTY FROM CHCDAT.LOTA LEFT JOIN CHCDAT.SERH s ON  J0ASER = s.HVSERN AND s.HVTRNT = 'C' AND TIMESTAMP(s.HVTDAT,s.HVTIME) = J0STIM \n" +
							  "\tLEFT JOIN CHCDAT.SERC s2 ON s2.HWTRAN = S.HVTRAN WHERE J0ASER = ? AND J0RTYP = '1'")) {

			 pst.setString(1, query);
			 ResultSet rs = pst.executeQuery();

			 if (rs.next()) {
				 String j0aser = rs.getString("J0ASER");
				 String j0stim = rs.getString("J0STIM");
				 String j0part = rs.getString("J0APRT");
				 String j0seq = rs.getString("J0ALOT");
				 String hwqty = rs.getString("HWQTY");

				 // 创建根节点
				 root = new Node(j0aser, 0, j0stim, j0part, j0seq,hwqty);
			 } else {
				 return Result.error("未找到对应的记录！");
			 }
		 } catch (SQLException e) {
			 e.printStackTrace();
			 return Result.error("数据库查询失败！");
		 }
//		 7340694
		 // 执行递归查询
		 fetchHierarchy(query, root);
		 // 返回根节点，保留树形结构
		 // 将根节点放入列表中并返回
		 List<Node> result = new ArrayList<>();
		 result.add(root);
		 return Result.OK(result);
	 }

	 // 递归函数
	 private static void fetchHierarchy(String j0seri, Node parentNode) {
		 // 当前级别的查询
		 try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
			  PreparedStatement pst = connection.prepareStatement(
					  "SELECT J0ASER, J0STIM, J0APRT, J0ALOT,DECIMAL(s2.HWQTY,10,2) AS HWQTY FROM CHCDAT.LOTA LEFT JOIN CHCDAT.SERH s ON  J0ASER = s.HVSERN AND s.HVTRNT = 'C' AND TIMESTAMP(s.HVTDAT,s.HVTIME) = J0STIM \n" +
							  "\tLEFT JOIN CHCDAT.SERC s2 ON s2.HWTRAN = S.HVTRAN WHERE J0SERI = ? AND J0RTYP = '1' AND J0ASEQ = '0' AND J0SEQ# !='0' ")) {

			 pst.setString(1, j0seri);
			 ResultSet rs = pst.executeQuery();

			 while (rs.next()) {
				 String j0aser = rs.getString("J0ASER");
				 String j0stim = rs.getString("J0STIM");
				 String j0part = rs.getString("J0APRT");
				 String j0seq = rs.getString("J0ALOT");
				 String hwqty = rs.getString("HWQTY");

				 // 创建当前节点并根据父节点设置其级别
				 Node currentNode = new Node(j0aser, parentNode.level + 1, j0stim, j0part, j0seq,hwqty);
				 parentNode.addChild(currentNode); // 将当前节点添加为父节点的子节点

				 // 递归调用查看下一个级别
				 fetchHierarchy(j0aser, currentNode);
			 }
		 } catch (SQLException e) {
			 e.printStackTrace();
		 }
	 }

	 @GetMapping(value = "/agvquery/materialquery")
	 public Response handleRequest(Request request) {
		 String sql = "SELECT J0PART, s.HTLOTN, (s.HTQTY - s.HTQTYC) AS qty, l.J0STIM "
				 + "FROM CHCDAT.LOTA l "
				 + "INNER JOIN CHCDAT.SERI s ON l.J0SERI = s.HTSERN "
				 + "WHERE l.J0SERI = ? "  // 参数化查询防注入
				 + "ORDER BY J0STIM DESC LIMIT 1";

		 Response response = new Response();
		 response.setDesc("V254 HF");  // 固定值

		 try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
			  PreparedStatement pstmt = conn.prepareStatement(sql)) {

			 pstmt.setString(1, request.getBarinfo());  // 绑定参数

			 try (ResultSet rs = pstmt.executeQuery()) {
				 if (rs.next()) {
					 // 结果集映射
					 response.setMaterialcode(rs.getString("J0PART"));
					 response.setBatchcode(rs.getString("HTLOTN"));
					 response.setNumber(rs.getInt("qty"));

					 // 时间格式化（去掉毫秒）
					 Timestamp timestamp = rs.getTimestamp("J0STIM");
					 if (timestamp != null) {
						 response.setCreatetime(
								 timestamp.toLocalDateTime()
										 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
										 .replaceFirst("\\.\\d+", "")
						 );
					 }
				 } else {
					 // 无数据时保持默认值
					 response.setMaterialcode("HSB90700");
				 }
			 }
		 } catch (SQLException e) {
			 // 添加日志记录
			 e.printStackTrace();
		 }

		 return response;
	 }

	 // 新增自定义Response类（添加在Node类同级位置）
	 static class Response {
		 private String desc;
		 private String materialcode;
		 private String batchcode;
		 private int number;
		 private String createtime;

		 // getter/setter 省略（需根据实际业务补充完整）
		 public void setDesc(String desc) { this.desc = desc; }
		 public void setMaterialcode(String materialcode) { this.materialcode = materialcode; }
		 public void setBatchcode(String batchcode) { this.batchcode = batchcode; }
		 public void setNumber(int number) { this.number = number; }
		 public void setCreatetime(String createtime) { this.createtime = createtime; }
	 }

	 // 新增Request类（若不存在）
	 static class Request {
		 private String barinfo;
		 public String getBarinfo() { return barinfo; }
	 }

	 static class Node {
		 String j0aser;
		 int level;
		 String j0stim;
		 String j0part;
		 String j0seq;
		 String hwqty;
		 List<Node> children; // 子节点

		 Node(String j0aser, int level, String j0stim, String j0part, String j0seq, String hwqty) {
			 this.j0aser = j0aser;
			 this.level = level; // 直接设定级别
			 this.j0stim = j0stim;
			 this.j0part = j0part;
			 this.j0seq = j0seq;
			 this.hwqty = hwqty;
			 this.children = new ArrayList<>(); // 初始化子节点列表
		 }

		 // 添加子节点
		 void addChild(Node child) {
			 this.children.add(child);
		 }

		 // 添加getter方法
		 public String getJ0aser() {
			 return j0aser;
		 }

		 public int getLevel() {
			 return level;
		 }

		 public String getJ0stim() {
			 return j0stim;
		 }

		 public String getJ0part() {
			 return j0part;
		 }

		 public String getJ0seq() {
			 return j0seq;
		 }

		 public String getHwqty() {
			 return hwqty;
		 }

		 public void setHwqty(String hwqty) {
			 this.hwqty = hwqty;
		 }

		 public List<Node> getChildren() {
			 return children;
		 }
	 }
}
